# encoding = utf-8
import pickle

from scipy import interpolate

from application.logging import logger
from application.model.outside_temperature.connect_mysql_read_weather_data import connect_mysql_read_weather_data
from application.model.outside_temperature.get_model_path_by_model_name import get_model_path_by_model_name
from application.model.outside_temperature.get_weather_timestamp_list import get_weather_timestamp_list


def get_wind_model(area_code):
    """
    生成风速模型
    :param area_code: 地区编码
    :return: 模型名称
    """
    # 获取数据:天气数据
    data = connect_mysql_read_weather_data(area_code=area_code)
    # 打印数据
    logger.info(f"天气数据:\n{data}")
    try:
        # 时间列表:时间戳
        time_ = get_weather_timestamp_list(data=data)
        # 打印数据
        logger.info(f"时间列表: {len(time_)} - {time_}")
        # 数据转换
        data['winp'] = data['winp'].str.strip("级").astype(int)
        # 数据列表
        wind = list(data["winp"])
        logger.info(f"风速列表: {len(wind)} - {wind}")
        # 训练数据
        x, y = time_, wind
        # 打印数据
        logger.info(f"训练数据:\n x:{len(x)}-{x}\n y:{len(y)}-{y}")
        # 训练模型
        f = interpolate.interp1d(x, y, kind="nearest")
        print(f)
        # 模型名称
        model_name = f"cha_zhi_cubic_wind_{area_code}.pkl"
        logger.info(f"模型名称: {model_name}")
        # 模型路径
        model_path = get_model_path_by_model_name(model_name=model_name)
        logger.info(f"模型路径: {model_path}")
        # 存储模型
        pickle.dump(f, open(model_path, "wb"))
        # 存储成功
        logger.info(f"生成风速模型成功: {model_path}")
        return model_name
        pass
    except BaseException as err:
        logger.error(f"生成风速模型失败: {err}")
        pass
    pass


if __name__ == '__main__':
    get_wind_model(area_code="110106000000")
    pass
